// 管制药品统计
import React from 'react';
import { Card, Row, Col, DatePicker, Select, Button, message, Form } from 'antd';
import { handleExcel } from 'tools/handleExcel.js';
import store from 'store';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import './style/index.less';
import PubilcTablePagination from 'pages/common/PubilcTablePagination';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import 'assets/css/common.css';

let {Option} = Select;

class ControlledDrugsStatistics extends React.Component {
    constructor() {
        super();
        this.state = {
            basicHeight: 0,
            tableData: [],
            page: 1,
            pageSize: 20,
            total: 0,
            columns: [],
            widthTotal: 0, // table总宽度
            typeSelectData: [], // 类型下拉框数据
            parameterSetting: {}, // 默认输入框数据
            loading: false
        }
    }

    componentDidMount() {
        this.getMainTableColumns();
        this.getParameterSetting();
        this.getPoisonSelectData();
        // 关闭loading
        this.child.handleLoading();
        this.setState({basicHeight: document.getElementById("controlled-drugs-statistics-basic").clientHeight})
    }

    onRef = (ref) => {
        this.child = ref
    }

    // 获取默认参数配置
    getParameterSetting = () => {
        let data = {
			params: []
		}
		$http.post('urlS', this, {
			code: "02050001",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    this.setState({
                        parameterSetting: res.result[0] ? res.result[0] : {},
                    })
				}
            }
		})
    }

    // 3.2.1.9.2.获取管制药品统计界面类型下来数据集
    getTypeSelectData = () => {
        if(this.state.typeSelectData&&this.state.typeSelectData.length > 0) {
            return;
        }
        let data = {
			params: []
		}
		$http.post('urlS', this, {
			code: "02050002",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    this.setState({typeSelectData: res.result})
				}
			}
		})
    }

    // 3.2.1.9.3.获取管制分类字典
    getPoisonSelectData = () => {
        if(this.state.poisonSelectData&&this.state.poisonSelectData.length > 0) {
            return;
        }
        let data = {
			params: []
		}
		$http.post('urlS', this, {
			code: "02050003",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
                    this.setState({poisonSelectData: res.result})
				}
			}
		})
    }

    // 获取主列表columns
    getMainTableColumns = () => {
        let data = {
			params: [{
                compontName: "ConTrolDrugList", // 病人登记号/证件号
                type: 'C', // 卡类型id
            }]
		}
		$http.post('urlS', this, {
			code: '01040073',
			data: data,
			success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                        return  {
                            ...item,
                            key: index + 1,
                            title: <div onDoubleClick={() => this.mainColumnRef.onOpenModel()}>{item.title}</div>
                        }
                    }) : '';
                    let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                    this.setState({columns: filterArr, widthTotal: res.totalWidth})
                }
			}
		})
    }

    onMainColumnRef = (ref) => {
        this.mainColumnRef = ref;
    }

    // 请求列表数据
	getTableData () {
        this.setState({loading: true});
        let { page, pageSize } = this.state;
        const { form: { validateFields } } = this.props;
        validateFields((errors, values) => {
            if (errors === null) {
                let data = {
                    params: [{
                        startDate: values.startDate ? Moment(values.startDate).format("YYYY-MM-DD") : Moment(), // 开始日期
                        endDate: values.endDate ? Moment(values.endDate).format("YYYY-MM-DD") : '', // 截止日期
                        phaTypeID: values.phaTypeID, // 类型ID
                        poisonID: values.poisonID, // 管制分类ID
                    }],
                    pagination:[{
                        pageSize: pageSize,
                        currentPage: page,
                        sortColumn: "Describe",
                        sortOrder: "asc"
                    }]
                }
                $http.post('urlS', this, {
                    code: "02050004",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0 && res.result) {
                            let arr = res.result[0].rows ? res.result[0].rows : [];
                            for (var i = 0; i < arr.length; i++) {
                                arr[i].key = i + 1
                            }
                            this.setState({tableData: arr, total: res.result[0].total, loading: false}, () => {
                                // 数据加载成功关闭loading
                                this.child.handleLoading()
                            })
                        } else {
                            this.setState({tableData: [], total: 0, loading: false}, () => {
                                // 数据加载成功关闭loading
                                this.child.handleLoading();
                            })
                        }
                    },
                    error: function () {
                        this.setState({tableData: [], total: 0, loading: false}, () => {
                            // 数据加载成功关闭loading
                            this.child.handleLoading();
                        })
                    }
                })
            }
        })
	}

    // 查询
    handleQuery = () => {
        this.setState({page: 1}, () => {
            this.getTableData()
        })
    }

    // 清屏
    resetFields = () => {
        this.props.form.resetFields();
        this.setState({tableData: [], total: 0})
    }

    // 导出
    exportTableData = () => {
        let {tableData, columns} = this.state;
        if (!(tableData&&tableData.length > 0)) {
            message.info("统计列表有数据时才支持导出功能");
            return;
        }
        const { form: { validateFields } } = this.props;
        validateFields((errors, values) => {
            if (errors === null) {
                let data = {
                    params: [{
                        startDate: values.startDate ? Moment(values.startDate).format("YYYY-MM-DD") : Moment(), // 开始日期
                        endDate: values.endDate ? Moment(values.endDate).format("YYYY-MM-DD") : '', // 截止日期
                        phaTypeID: values.phaTypeID, // 类型ID
                        poisonID: values.poisonID, // 管制分类ID
                    }],
                    pagination:[{
                        pageSize: 10000,
                        currentPage: 1,
                        sortColumn: "Describe",
                        sortOrder: "asc"
                    }]
                }
                $http.post('urlS', this, {
                    code: "02050004",
                    data: data,
                    success: function (res) { 
                        if (+res.errorCode === 0 && res.result) {
                            let arr = res.result[0].rows ? res.result[0].rows : [];
                            handleExcel.exportExcel(columns, arr, '管制药品统计');
                        }
                    }
                })
            }
        })
    }

    // 提供修改page和pageSize的回调函数
    compilePage(page, pageSize) {
        this.setState({page: page, pageSize: pageSize}, () => {
            // 重新调用查询方法
            this.getTableData();
        })
    }

    render() {
        let {parameterSetting, basicHeight, tableData, total, page, columns, widthTotal, typeSelectData, poisonSelectData, loading} = this.state;
        const { getFieldDecorator } = this.props.form;
        const formItemInput  = {
            labelCol: {span: 9},
            wrapperCol: {span: 15}
        };
        // 组件所需参数
		const param = {
			// 表头配置
			columns,
			// 表格数据
			data: tableData,
			// 数据总条数
			total,
			// 当前页数
			page,
			// 表格的宽度
			x: widthTotal,
			y: store.getState().tableHeight.y + 202 - 123 - basicHeight + 'px',
            height: store.getState().tableHeight.y + 202 - 77 - basicHeight + 'px',
            loading,
            pageSize: "20"
        }
        
        // 类型
		let typeOption = typeSelectData && typeSelectData.map((item, index) => {
			return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 管制分类
		let poisonOption = poisonSelectData && poisonSelectData.map((item, index) => {
			return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        return (
            <div className="controlled-drugs-statistics">
                <Card
                    size="small"
                    title={<div className="card-title-left-icon"><div></div>基本操作</div>}
                    id="controlled-drugs-statistics-basic"
                >
                    <Form>
                        <Row style={{marginTop: '12px'}}>
                            <Col span={3}>
                                <Form.Item label="开始日期" {...formItemInput}>
                                    {getFieldDecorator('startDate', {
                                        initialValue: parameterSetting.startDate ? Moment(parameterSetting.startDate) : Moment(),
                                    })(
                                        <DatePicker style={{width: '100%'}} />
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={3}>
                                <Form.Item label="截止日期" {...formItemInput}>
                                    {getFieldDecorator('endDate', {
                                        initialValue: parameterSetting.endDate ? Moment(parameterSetting.endDate) : Moment(),
                                    })(
                                        <DatePicker style={{width: '100%'}} />
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={3}>
                                <Form.Item label="类型" {...formItemInput}>
                                    {getFieldDecorator('phaTypeID', {
                                            initialValue: undefined,
                                        })(
                                            <Select
                                                showSearch optionFilterProp="seatchprop"
                                                allowClear
                                                placeholder="请选择"
                                                onFocus={this.getTypeSelectData}
                                            >
                                                {typeOption}
                                            </Select>
                                        )}
                                </Form.Item>
                            </Col>
                            <Col span={3}>
                                <Form.Item label="管制分类：" {...formItemInput} className="rules-position">
                                    {getFieldDecorator('poisonID', {
                                        initialValue: undefined,
                                        rules: [{ required: true, message: '请选择管制分类' }]
                                    })(
                                        <Select
                                            showSearch optionFilterProp="seatchprop" allowClear
                                            placeholder="请选择"
                                        >
                                            {poisonOption}
                                        </Select>
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={12} style={{marginTop: '4px'}}>
                                <Button onClick={this.handleQuery} style={{marginLeft: '150px'}}>查询</Button>
                                <Button
                                    type="dashed"
                                    style={{margin: '0 15px'}}
                                >打印</Button>
                                <Button
                                    type="dashed"
                                    onClick={this.exportTableData}
                                    style={{marginRight: '15px'}}
                                >导出</Button>
                                <Button
                                    type="primary"
                                    onClick={this.resetFields}
                                >清屏</Button>
                            </Col>
                        </Row>
                    </Form>
                </Card>
                <div style={{height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%'}}></div>
                <Card
                    size="small"
                    title={<div className="card-title-left-icon"><div></div>统计列表</div>}
                >
                    <div style={{height: store.getState().tableHeight.y + 202 - 30 - basicHeight + 'px', overflow: 'auto'}}>
                        <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
                    </div>
                </Card>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName='ConTrolDrugList'
                    configType="C"
                    onRef={this.onMainColumnRef}
                    reloadData={this.getMainTableColumns}
                />
            </div>
        )
    }
};
const ControlledDrugsStatisticsForm = Form.create()(ControlledDrugsStatistics);
export default ControlledDrugsStatisticsForm;